import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/books.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/models/book/BookSearchDto.dart';
import 'package:ichinesereader/models/book/categoryForSeries.dart';
import 'package:ichinesereader/pages/common/recommendedBooks.dart';
import 'package:ichinesereader/routes/routePages.dart';
import 'package:ichinesereader/themes/pageStyles.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:ichinesereader/widgets/layouts/appdrawerIndividual.dart';
import 'package:ichinesereader/widgets/layouts/appdrawerStudent.dart';
import 'package:ichinesereader/widgets/sidebars/individualSidebar.dart';
import 'package:ichinesereader/widgets/sidebars/studentSidebar.dart';

// ignore: must_be_immutable
class BooksRecommendBySeriesPage extends GetView<BooksController> {
  final box = Hive.box('appconfig');
  static const String routeName = '/student/books/recommendation';
  List<CategoryForSeries> booktags = [];

  Widget buildList() => GridView.builder(
        gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
          maxCrossAxisExtent: 250,
          crossAxisSpacing: 35,
          mainAxisSpacing: 35,
        ),
        padding: const EdgeInsets.all(8),
        itemCount: booktags.length,
        itemBuilder: (context, index) {
          final item = booktags[index];
          return GridTile(
            child: Container(
              margin: EdgeInsets.only(
                bottom: 54.0,
              ),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.all(
                  Radius.circular(6.0),
                ),
              ),
              child: InkWell(
                child: Ink.image(
                  image: Image.asset(item.image.toString()).image,
                  fit: BoxFit.cover,
                ),
                borderRadius: BorderRadius.all(Radius.circular(6.0)),
                onTap: () {
                  BookSearchDto bookSearchDto = new BookSearchDto();
                  if (booktags[index].text!.contains('&')) {
                    bookSearchDto.query =
                        booktags[index].text!.replaceAll(' ', '').split('&')[0];
                  } else {
                    bookSearchDto.query = booktags[index].text;
                  }
                  // controller.searchedBookItems.clear();
                  // controller.fetchSearchedBookItems(
                  //     0, 0, bookSearchDto, 'level');
                  Get.to(() => RecommendedBooksPage(
                      title: booktags[index].text.toString(),
                      bookSearchDto: bookSearchDto));
                },
              ),
            ),
            footer: GestureDetector(
              onTap: () {
                BookSearchDto bookSearchDto = new BookSearchDto();
                if (booktags[index].text!.contains('&')) {
                  bookSearchDto.query =
                      booktags[index].text!.replaceAll(' ', '').split('&')[0];
                } else {
                  bookSearchDto.query = booktags[index].text;
                }
                // controller.searchedBookItems.clear();
                // controller.fetchSearchedBookItems(0, 0, bookSearchDto, 'level');
                Get.to(() => RecommendedBooksPage(
                    title: booktags[index].text.toString(),
                    bookSearchDto: bookSearchDto));
              },
              child: Container(
                margin: EdgeInsets.only(
                  top: 60.0,
                ),
                decoration: BoxDecoration(
                  color: Get.isDarkMode
                      ? Get.theme.primaryColor.withOpacity(0.6)
                      : Get.theme.primaryColorDark.withOpacity(0.9),
                  borderRadius: BorderRadius.all(
                    Radius.circular(3),
                  ),
                ),
                padding: EdgeInsets.all(12),
                alignment: Alignment.center,
                child: Text(
                  item.text.toString().tr,
                  overflow: TextOverflow.fade,
                  style: TextStyle(
                      fontSize: 18,
                      color: Get.isDarkMode
                          ? Get.theme.primaryColorDark
                          : Get.theme.primaryColorLight),
                ),
              ),
            ),
          );
        },
      );

  @override
  Widget build(BuildContext context) {
    Log.debug('build book recommendations');
    bool isStudent = box.get(CacheManagerKey['nanhairole'].toString()) ==
        Constants.NanhaiRole_Student;
    bool isIndividual = box.get(CacheManagerKey['nanhairole'].toString()) ==
        Constants.NanhaiRole_Individual;
    PageStyles _pageStyles = PageStyles();

    if (isStudent | isIndividual) {
      booktags = [];
      Constants.recommendedTags.forEach(
        (key, value) {
          CategoryForSeries cate = CategoryForSeries();
          cate.image = value;
          cate.text = key;
          booktags.add(cate);
        },
      );
    }
    int _selectedSidebarItem = isStudent
        ? RoutePages.studentPageItems
            .indexWhere((page) => page.route == Get.currentRoute)
        : RoutePages.individualPageItems
            .indexWhere((page) => page.route == Get.currentRoute);

    final isSmallScreen =
        MediaQuery.of(context).size.width < Constants.DefinedScreenSmallSize;
    final isBigScreen =
        MediaQuery.of(context).size.width > Constants.DefinedScreenBigSize;

    return isStudent
        ? Container(
            decoration: _pageStyles.pageBoxDecoration(),
            child: Scaffold(
              backgroundColor: Colors.transparent,
              appBar: isSmallScreen
                  ? AppBar(
                      title: Text('Recommendations'.tr),
                    )
                  : null,
              drawer: isSmallScreen ? StudentAppDrawer() : null,
              body: Container(
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Visibility(
                        visible: !isSmallScreen,
                        child: StudentSidebarX(
                            selectedIndex: _selectedSidebarItem,
                            isBigScreen: isBigScreen)),
                    Expanded(
                      flex: 5,
                      child: Container(
                        margin: _pageStyles.mainContainerPageEdgeInsets(),
                        decoration: BoxDecoration(
                          color: Colors.white.withOpacity(0.1),
                        ),
                        child: buildList(),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          )
        : Container(
            decoration: _pageStyles.pageBoxDecoration(),
            child: Scaffold(
              backgroundColor: Colors.transparent,
              appBar: isSmallScreen
                  ? AppBar(
                      title: Text('Recommendations'.tr),
                    )
                  : null,
              drawer: isSmallScreen ? IndividualAppDrawer() : null,
              body: Container(
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Visibility(
                        visible: !isSmallScreen,
                        child: Container(
                            child: IndividualSidebarX(
                                selectedIndex: _selectedSidebarItem,
                                isBigScreen: isBigScreen))),
                    Expanded(
                      flex: 5,
                      child: Container(
                        decoration: BoxDecoration(
                          color: Colors.white.withOpacity(0.1),
                          borderRadius: BorderRadius.circular(3.0),
                        ),
                        margin: _pageStyles.mainContainerPageEdgeInsets(),
                        child: buildList(),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          );
  }
}
